<!--
 * @Author: Wangtao
 * @Date: 2022-08-31 16:05:21
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-09-20 14:56:46
-->
<template>
  <div class="box" :class="{ 'record-box': !isCallCard, 'callcard-box': isCallCard }">
    <div class="empty" v-if="!templateEnable">
      <title-content class="empty-box" :title="'服务小计'" :maxTitle="false" :adaption-height="true">
        <template v-slot:content>
          <img :src="emptyImg" />
          <p class="text">服务小计表单已被禁用</p>
        </template>
        <template v-slot:title-oprate>
          <div class="log-box" @click="viewLog">查看日志</div>
        </template>
      </title-content>
    </div>
    <title-content v-else :isoprate="true" :title="'服务小计'" :maxTitle="false" :adaption-height="true">
      <template v-slot:content>
        <div class="info">
          <dynamic-form
            class="dynamic-form"
            :scenes="'callCenter'"
            :type="formType"
            :form="form"
            ref="customerFormRef"
            @onChangeTemStatus="onChangeTemStatus"
          ></dynamic-form>
        </div>
      </template>
      <template v-slot:title-oprate>
        <div class="log-box" @click="viewLog">查看日志</div>
      </template>
      <template v-slot:oprate>
        <div class="oprate">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="insertNode">保存</el-button>
        </div>
      </template>
    </title-content>
    <!-- <div class="info">
      <div class="log-box" @click="viewLog">查看日志</div>
      <dynamic-form
        class="dynamic-form"
        :scenes="'callCenter'"
        :type="formType"
        :form="form"
        ref="customerFormRef"
        @onChangeTemStatus='onChangeTemStatus'
      ></dynamic-form>
    </div>
    <div class="oprate">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="insertNode">保存</el-button>
    </div> -->
    <move-dialog
      :visible="show"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      width="720px"
      customClass="service-note"
      title="服务小记日志"
    >
      <resize-table
        :showPagination="true"
        :data="tableData"
        :pagingData="pagingData"
        @onPageChange="handleCurrentChange"
        @onPageSizeChange="handleSizeChange"
        :headers="headers"
        :height="300"
      >
        <template #fields="{ scope }">
          <div
            v-for="v in scope.row.fields"
            :key="v._id"
            :class="[fieldId('attachments'), fieldId('serviceLabel')].includes(v._id) ? 'file-field' : 'dy-field'"
          >
            <el-tooltip :content="v.defaultName + ': ' + v.defaultValue" placement="top" effect="light">
              <span>{{ v.defaultName }}:</span>
            </el-tooltip>
            <template v-if="v._id === fieldId('attachments')">
              <!-- 附件 -->
              <template v-if="v.defaultValue && v.defaultValue.length">
                <span v-for="(val, idx) in v.defaultValue" :key="idx" class="file">
                  <a :href="val.url" :download="val.fileName" target="_blank">
                    {{ val.fileName }}
                  </a>
                  <i class="MC_iconfont MC_icon-yulan-yulan" @click="preview(v.defaultValue, val)"></i>
                </span>
              </template>
              <template v-else> -- </template>
            </template>
            <template v-else-if="v._id === fieldId('serviceLabel')">
              <!-- 服务标签 -->
              <template v-if="v.defaultValue && v.defaultValue.length">
                <el-tag
                  v-for="(item, index) in v.defaultValue"
                  :key="index"
                  :color="item.color"
                  :style="{
                    color: item.color === '#FFFFFF' || item.color === '#fff' || !item.color ? '#252c32' : '#ffffff'
                  }"
                >
                  <el-tooltip :content="item.name" placement="top" effect="light">
                    {{ item.name }}
                  </el-tooltip>
                </el-tag>
              </template>
              <template v-else> -- </template>
            </template>
            <template v-else>
              <el-tooltip :content="v.defaultName + ': ' + v.defaultValue" placement="top" effect="light">
                {{ v.defaultValue }}
              </el-tooltip>
            </template>
          </div>
        </template>
      </resize-table>
    </move-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, computed, watch, getCurrentInstance } from 'vue'
import dynamicForm from '@app/customer/components/dynamic-form.vue'
import { saveServerNode } from '@app/base/apis/call'
// import mcScrollBar from '@app/call-center/views/recent-calls/component/tab-component/common/mc-scrollbar.vue'
import { deepClone } from '@/common/utils/common'
import { ElMessage } from 'element-plus'
import moveDialog from '@/common/components/move-dialog/index.vue'
import resizeTable from '@common/components/resize-table/index.vue'
import { serverNodeLog } from '@app/base/apis/call'
import { commonStore } from '@/common/store/modules/common'
import previewFile from '@/common/components/preview/index'
import { validPairs, getParams, handlePairs } from '@app/customer/mixins/index'
import titleContent from '@app/call-center/views/recent-calls/component/tab-component/customDetail/title-content.vue'
import emptyImg from '@/common/assets/empty-img/service-record.svg'
export default defineComponent({
  name: 'callDynamicBi',
  components: {
    dynamicForm,
    // mcScrollBar,
    moveDialog,
    resizeTable,
    titleContent
  },
  props: {
    // 场景值 callcard 通话卡片 callrecord 通话记录详情
    scene: {
      type: String,
      default: 'callcard'
    },
    // 匹配客户列表
    customerList: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 卡片信息-通话卡片
    cardInfo: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 通话详情信息
    callRcordInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  // ----------------生命周期-----------------------
  setup(props) {
    // ----------------传入属性-----------------------
    // ----------------内部属性-----------------------
    const instance: any = getCurrentInstance()
    const state = reactive({
      show: false,
      visible: false,
      form: {},
      async insertNode() {
        instance?.refs.customerFormRef.isCheckForm().then(async (valid: any) => {
          if (valid.status) {
            const saveForm = deepClone(valid.form)
            const sendForm = {
              fields: getParams(saveForm),
              callId: props.cardInfo.superUniqueId,
              showBack: saveForm
            }
            const res = await saveServerNode(sendForm)
            if (res.success) {
              ElMessage.success('保存记录成功！')
            }
          }
        })
      },
      cancel() {
        state.form = {}
      },
      // 分页数据
      pagingData: { page: 1, total: 0, limit: 10 },
      // 表头数据
      headers: [
        { label: '操作人', prop: 'createAgent', show: true, width: 100 },
        { label: '操作时间', prop: 'createTime', show: true, width: 100 },
        { label: '内容', prop: 'fields', show: true, custom: true }
      ],
      tableData: [],
      formType: 'add',
      templateEnable: true,
      onChangeTemStatus(status: boolean) {
        // 服务小计模板是否开启
        console.log('服务小计模板是否开启', status)
        state.templateEnable = status
      }
    })
    // ----------------计算属性-----------------------

    // ----------------监听方法-----------------------
    const isCallCard = computed(() => {
      return props.scene === 'callcard'
    })

    const handleCurrentChange = (page: number) => {
      state.pagingData.page = page
      getLogs()
    }

    const handleSizeChange = (size: number) => {
      state.pagingData.limit = size
      getLogs()
    }

    const viewLog = () => {
      state.show = true
      getLogs()
    }

    const closeDialog = () => {
      state.show = false
    }

    const fieldId = (field: string) => {
      const obj = commonStore().publicCache.globalFieldCacheObj[field] || {}
      if (obj) {
        return obj._id
      }
      return ''
    }

    const getAgentName = (id: string) => {
      const obj = commonStore().publicCache.userCacheObj[id] || {}
      if (obj.agentName) {
        return obj.agentName + '[' + obj.agentNumber + ']'
      }
      return '--'
    }

    const getLogs = () => {
      const params = {
        limit: state.pagingData.limit,
        page: state.pagingData.page,
        callId: props.cardInfo.superUniqueId
      }
      serverNodeLog(params).then((res) => {
        if (res.success && res.data) {
          res.data.list.forEach((v: any) => {
            v.createAgent = getAgentName(v.createAgent)
          })
          if (res.data && res.data.list && res.data.list[0] && res.data.list[0].showBack) {
            state.formType = 'edit'
            state.form = res.data.list[0].showBack
          } else {
            state.formType = 'add'
            state.form = {}
          }
          state.tableData = res.data.list || []
          state.pagingData.total = res.data.count || 0
        }
      })
    }

    const preview = (arr: any, row: any) => {
      previewFile({
        list: arr,
        img: row,
        isHiddenDelBtn: false
      })
    }

    watch(
      props,
      (props: any) => {
        if (props.cardInfo.superUniqueId) {
          getLogs()
        }
      },
      {
        immediate: true
      }
    )

    // ----------------调用方法-----------------------
    return {
      ...toRefs(state),
      isCallCard,
      viewLog,
      closeDialog,
      fieldId,
      preview,
      emptyImg,
      handleCurrentChange,
      handleSizeChange
    }
  }
})
</script>
<style lang="stylus">
.service-note
  .el-dialog__footer
    padding 10px 0 0
</style>
<style lang="stylus" scoped>
.resize-table
  position static !important
.record-box
  .info
    width 100%
    position relative
.callcard-box
  .log-box,.dynamic-form
    width 50%
.box
  width 100%
  padding-top: 24px
  height: 100%
  box-sizing: border-box
  position relative
  :deep(.title-content)
    height 100%
  .empty
    position relative
    width 100%
    height 100%
    background white
    .empty-box
      height 100%
      :deep(.content)
        display flex
        flex-direction: column
        justify-content: center
        align-items: center
        img
          width 300px
        .text
          font-size 14px
          font-weight 400
          color rgba(0, 0, 0, 0.6)
  .log-box
    display: flex
    justify-content: flex-end
    color var(--mc-main-color)
  .info
    height: calc(100% - 60px)
    overflow: auto;
    padding-top 30px
  .oprate
    height 100%
    // position: absolute
    width 100%
    bottom 0
    display: flex
    justify-content: flex-end
    border-top: 1px solid var(--mc-gray3-color);
    box-sizing: border-box
    align-items: center
    z-index 10000
    background-color white
.dy-field, .file-field
    width 100%
    display block
    color rgba(0, 0, 0, 0.38)
    font-size 14px
    &.dy-field
      overflow hidden
      text-overflow ellipsis
      white-space nowrap
    .el-tag
      margin 0 6px 4px 4px
    span
      color rgba(0, 0, 0, 0.6)
    .file
      display inline-block
      background #F1F8FD
      padding 3px 4px
      margin 0 6px 4px 4px
      i
        font-size 14px
        cursor pointer
        margin-left 4px
        color var(--mc-main-color)
</style>
